package chatbot;

import chatbot.base.ChatBot;
import java.util.prefs.*;
import chatbot.base.*;
import chatbot.base.event.*;

public class SimpleChatBot implements ChatBot {
    Preferences prefs;
    boolean isDebug;
    ChatConnection c;
    Event start, end;

    public SimpleChatBot() {
        prefs = Preferences.systemNodeForPackage (getClass ());
        isDebug = Boolean.parseBoolean(prefs.get("chatbot.debug", "true"));
        try {
            c = (ChatConnection)Class.forName(prefs.get("chatbot.protocol", "chatbot.irc.IRCConnection")).newInstance();
            c.setPreferences(prefs);
        } catch(Exception e) {
            System.err.println("Failed to load 'chatbot.protocol'.");
        }
        start = new ChatBotEvent("ChatBotStart", this);
        end = new ChatBotEvent("ChatBotEnd", this);
        try {
            ChatBotEvent.getEventManager().registerEvent(start);
            ChatBotEvent.getEventManager().registerEvent(end);
        } catch (Exception e) {
            System.err.println("Failed to register ChatBot events.");
        }
        if (this.isDebug()) {
            System.err.println("SimpleChatBot loaded.");
        }
    }
    
    public Preferences getPreferences() {
        return prefs;
    }
    
    public boolean isDebug() {
        return isDebug;
    }

    public void start() {
        start.alertListeners();
        try {
            c.connect();
        } catch (Exception e) {

        }
        if (this.isDebug()) {
            System.err.println("SimpleChatBot running.");
        }
    }

    public void end() {
        end.alertListeners();
        c.disconnect();
        if (this.isDebug()) {
            System.err.println("SimpleChatBot ended.");
        }
    }
}
